package com.duojuhe.basic.captcha.service.impl;

import com.duojuhe.cache.CaptchaCache;
import com.duojuhe.basic.captcha.dto.CaptchaRes;
import com.duojuhe.basic.captcha.service.KaptchaService;
import com.duojuhe.common.exception.base.DuoJuHeException;
import com.duojuhe.common.result.ErrorCodes;
import com.duojuhe.common.result.ServiceResult;
import com.duojuhe.common.utils.idgenerator.UUIDUtils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

@Slf4j
@Component
public class KaptchaServiceImpl implements KaptchaService {
   @Resource
   private CaptchaCache captchaCache;
   @Resource
   private DefaultKaptcha defaultKaptcha;
    /**
     * 获得图形验证码
     *
     * @return
     * @throws Exception
     */
    @Override
    public ServiceResult getCaptchaImageCode() throws Exception{
        String createText = defaultKaptcha.createText();
        String imageId = UUIDUtils.getUUID32();
        ByteArrayOutputStream imgByte = new ByteArrayOutputStream();
        BufferedImage img = defaultKaptcha.createImage(createText);
        ImageIO.write(img, "jpg", imgByte);
        byte[] bytes = imgByte.toByteArray();
        CaptchaRes captchaRes = new CaptchaRes();
        captchaRes.setImageId(imageId);
        captchaRes.setImageCode("data:image/jpeg;base64," + Base64Utils.encodeToString(bytes));
        captchaCache.putCaptchaCache(imageId,createText);
        return ServiceResult.ok(captchaRes);
    }


    /**
     * 校验图形验证码
     *
     * @param imageId
     * @param imageCode
     * @return
     */
    @Override
    public void verifyCaptchaCode(String imageId, String imageCode) {
        try {
            if (StringUtils.isBlank(imageCode) || StringUtils.isBlank(imageId)) {
                throw new DuoJuHeException(ErrorCodes.CAPTCHA_CODE_ERROR);
            }
            //key
            String captchaKey = imageId + imageCode;
            if(StringUtils.isBlank(captchaCache.getCaptchaCacheByCaptchaKey(captchaKey))){
                throw new DuoJuHeException(ErrorCodes.CAPTCHA_CODE_ERROR);
            }
            captchaCache.invalidateCaptchaCacheByCaptchaKey(captchaKey);
        } catch (Exception e) {
            throw new DuoJuHeException(ErrorCodes.CAPTCHA_CODE_ERROR);
        }
    }

}
